﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using Business;
using Entity;
using Entity.Custom;
using Newtonsoft.Json;
using Utilities;

namespace FreshCms.BackEnd.Handler
{
    /// <summary>
    /// Summary description for UploadImage
    /// </summary>
    public class UploadImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        #region Declare variable for check pms
        Int32 ui = 0;
        InPms chkPms = new InPms();
        InUser CurrentUser = new InUser();
        #endregion

        public void ProcessRequest(HttpContext context)
        {
            string m = "";
            var response = new ResponseData();

            #region Get PanelId and Check Psm
            CurrentUser = InUserBusiness.GetSessionInUser();
            if (!string.IsNullOrEmpty(context.Request["ui"]))
            {
                Int32.TryParse(context.Request["ui"], out ui);
                if (ui > 0)
                    chkPms = InPmsBusiness.CheckSessionPms(ui);
                if (chkPms == null)
                    chkPms = new InPms { PmsView = 0, PmsUpdate = 0, PmsDelete = 0 };
            }
            #endregion

            if (context.Request.RequestType == "POST")
            {
                if (context.Request["m"] != null)
                    m = context.Request["m"];
                else
                    return;
            }
            else
            {
                if (context.Request.QueryString["m"] != null)
                    m = context.Request.QueryString["m"];
                else
                    return;
            }

            switch (m.ToLower())
            {
                case "uploadimage":
                    response = UploadAvatar(context);
                    break;
                case "uploadavatarproduct":
                    response = UploadAvatarProduct(context);
                    break;
                case "uploadavatarnew":
                    response = UploadAvatarNew(context);
                    break;
                case "uploadgallery":
                    response = UploadGallery(context);
                    break;
                case "uploadavatarbox":
                    response = UploadAvatarBox(context);
                    break;  
                    
            }

            context.Response.ContentType = "application/x-javascript";

            string callBack = context.Request["callback"];
            if (!string.IsNullOrEmpty(callBack))
            {
                context.Response.Write(callBack + "( " + JsonConvert.SerializeObject(response) + " );");
            }
            else
                context.Response.Write(JsonConvert.SerializeObject(response));
        }

        private ResponseData UploadAvatarBox(HttpContext context)
        {
            var response = new ResponseData();

            if (context.Request.Files.Count > 0)
            {
                int typebox = Utils.GetQuery("typebox", 0);
                int boxcate = Utils.GetQuery("boxcate", 0);
                int boxid = Utils.GetQuery("boxid", 0);
                int w = Utils.GetQuery("w", 0);
                int h = Utils.GetQuery("h", 0);
                string urlImg = "";
                var extention = Path.GetExtension(context.Request.Files[0].FileName);
                string path = Utils.GetUploadForAvatarBox(typebox);
                path = path + Utils.GenerateAvatarName(extention);

                string mappath = context.Server.MapPath(path);
                FileInfo file = new FileInfo(mappath);
                DirectoryInfo dir = file.Directory;
                if (!dir.Exists) dir.Create();
                HttpPostedFile postedFile = context.Request.Files[0];
                postedFile.SaveAs(mappath);

                var objThumb = new Thumbnailv2.Thumbnail();
                objThumb.InputImage = mappath;
                objThumb.W = w;
                objThumb.H = h;
                objThumb.CreateThumb();

                var returnVal = OutBoxBusiness.UpdateAvatar(boxid, path);
                if (returnVal>=0)
                {
                    response.Success = true;
                    response.Message = "Upload thanh cong";
                    response.Data = boxid;
                    response.ExtData = path + ".thumb" + w + "x" + h + ".jpg";    
                }
                else
                {
                    response.Success = false;
                    response.Message = "Update ảnh đại diện không thành công.";
                    response.Data = boxid;
                    response.ExtData = path + ".thumb" + w + "x" + h + ".jpg";
                }

            }

            return response;
        }

        private ResponseData UploadGallery(HttpContext context)
        {
            // Check Pms
            if (chkPms.PmsUpdate == 0)
                return new ResponseData { Data = null, ExtData = null, Message = Constant.PmsNoUpdate, Success = false };

            var response = new ResponseData();
            if (!string.IsNullOrEmpty(context.Request["type"])
                && !string.IsNullOrEmpty(context.Request["id"]))
            {
                Int32 type = 0;
                Int32.TryParse(context.Request["type"], out type);
                Int32 id = 0;
                Int32.TryParse(context.Request["id"], out id);

                // Check Role, phai dung ng viet bai thi moi dc upload gallery
                int flag = 0;
                // Check neu User la SuperAdmin ( quyền sửa tất cả ) thì cho UPDATE luôn, không cần check UserID
                if (CurrentUser.IsSuperAdmin == 1)
                    flag = 1;
                else
                {
                    if(type==0) // neu la gallery san pham
                        flag = OutProductBusiness.CheckRole(CurrentUser.UserId, id);
                    else // neu la gallery tin tuc
                        flag = OutNewBusiness.CheckRole(CurrentUser.UserId, id);
                }
                if(flag>0)
                {
                    string path = Utils.GetUploadForGallery(type, id);
                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        var extention = Path.GetExtension(context.Request.Files[i].FileName);
                        string pathUpload = "";
                        pathUpload = path + Utils.GenerateFileName(extention);

                        string mappath = context.Server.MapPath(pathUpload);
                        FileInfo file = new FileInfo(mappath);
                        DirectoryInfo dir = file.Directory;
                        if (!dir.Exists) dir.Create();
                        HttpPostedFile postedFile = context.Request.Files[i];
                        postedFile.SaveAs(mappath);

                        var objThumb = new Thumbnailv2.Thumbnail();
                        objThumb.InputImage = mappath;

                        if (type == 0) // gallery product
                        {
                            objThumb.W = Constant.GalleryProThumbW;
                            objThumb.H = Constant.GalleryProThumbH;
                        }
                        else // gallery news
                        {
                            objThumb.W = Constant.GalleryNewThumbW;
                            objThumb.H = Constant.GalleryNewThumbH;
                        }

                        string pathThumb = path + objThumb.CreateThumb();
                        response.Data = pathUpload;
                        response.ExtData = pathThumb;
                        response.Success = true;
                        response.Message = "Upload thanh cong";
                        // INSERT gallery 
                        var objGal = new OutGallery {GalleryImg = pathUpload, GalleryThumb = pathThumb};
                        if(type==0)
                        {
                            objGal.NewId = 0;
                            objGal.ProId = id;
                        }else
                        {
                            objGal.NewId = id;
                            objGal.ProId = 0;
                        }
                        response.Total = OutGalleryBusiness.InsertOutGallery(objGal);

                        if (type == 0)
                        {
                            // ghi log he thong
                            InLogBusiness.InsertInLog(new InLog
                            {
                                UserId = CurrentUser.UserId,
                                LogAction = 1,
                                Field1 = "Upload ảnh Gallery cho sản phẩm thành công",
                                Field2 = "Id sản phẩm: " + id,
                                Field3 = "",
                                LogId = 0
                            });
                        }
                        else
                        {
                            // ghi log he thong
                            InLogBusiness.InsertInLog(new InLog
                            {
                                UserId = CurrentUser.UserId,
                                LogAction = 1,
                                Field1 = "Upload ảnh Gallery cho tin bài thành công",
                                Field2 = "Id tin bài: " + id,
                                Field3 = "",
                                LogId = 0
                            });
                        }

                        
                    }
                }else
                {
                    response.Data = flag;
                    if (type == 0) // neu la gallery san pham
                        response.Message = "Sản phẩm này không do bạn tạo ra. Bạn không có quyền upload ảnh cho sản phẩm này.";
                    else // neu la gallery tin tuc
                        response.Message = "Tin bài này không do bạn tạo ra. Bạn không có quyền upload ảnh cho tin bài này.";
                    response.Success = false;
                }
                
            }
            return response;
        }

        private ResponseData UploadAvatar(HttpContext context)
        {
            var response = new ResponseData();

            if (context.Request.Files.Count > 0)
            {
                var extention = Path.GetExtension(context.Request.Files[0].FileName);
                string path = Utils.GetUploadForAvatarUser();
                path = path + Utils.GenerateFileName(extention);

                string mappath = context.Server.MapPath(path);
                FileInfo file = new FileInfo(mappath);
                DirectoryInfo dir = file.Directory;
                if (!dir.Exists) dir.Create();
                HttpPostedFile postedFile = context.Request.Files[0];
                postedFile.SaveAs(mappath);

                var objThumb = new Thumbnailv2.Thumbnail();
                objThumb.InputImage = mappath;
                objThumb.W = Constant.InUserAvatarWidth;
                objThumb.H = Constant.InUserAvatarHeight;
                objThumb.CreateThumb();
                objThumb = null;

                response.Success = true;
                response.Message = "Upload thanh cong";
                response.Data = path;

            }

            return response;
        }

        private ResponseData UploadAvatarProduct(HttpContext context)
        {
            var response = new ResponseData();

            if (context.Request.Files.Count > 0)
            {
                var extention = Path.GetExtension(context.Request.Files[0].FileName);
                string path = Utils.GetUploadForAvatarProduct();
                path = path + Utils.GenerateAvatarName(extention);

                string mappath = context.Server.MapPath(path);
                FileInfo file = new FileInfo(mappath);
                DirectoryInfo dir = file.Directory;
                if (!dir.Exists) dir.Create();
                HttpPostedFile postedFile = context.Request.Files[0];
                postedFile.SaveAs(mappath);

                var objThumb = new Thumbnailv2.Thumbnail();
                objThumb.InputImage = mappath;
                objThumb.W = Constant.ProductAvatar1Width;
                objThumb.H = Constant.ProductAvatar1Height;
                objThumb.CreateThumb();

                if (Constant.ProductAvatar2Width > 0 && Constant.ProductAvatar2Height >0)
                {
                    objThumb.W = Constant.ProductAvatar2Width;
                    objThumb.H = Constant.ProductAvatar2Height;
                    objThumb.CreateThumb();    
                }

                if (Constant.ProductAvatar3Width > 0 && Constant.ProductAvatar3Height > 0)
                {
                    objThumb.W = Constant.ProductAvatar3Width;
                    objThumb.H = Constant.ProductAvatar3Height;
                    objThumb.CreateThumb();
                }

                objThumb = null;

                response.Success = true;
                response.Message = "Upload thanh cong";
                response.Data = path;
                response.ExtData = path + ".thumb" + Constant.ProductAvatar1Width + "x" + Constant.ProductAvatar1Height + ".jpg";
            }

            return response;
        }

        private ResponseData UploadAvatarNew(HttpContext context)
        {
            var response = new ResponseData();

            if (context.Request.Files.Count > 0)
            {
                var extention = Path.GetExtension(context.Request.Files[0].FileName);
                string path = Utils.GetUploadForAvatarNew();
                path = path + Utils.GenerateAvatarName(extention);

                string mappath = context.Server.MapPath(path);
                FileInfo file = new FileInfo(mappath);
                DirectoryInfo dir = file.Directory;
                if (!dir.Exists) dir.Create();
                HttpPostedFile postedFile = context.Request.Files[0];
                postedFile.SaveAs(mappath);

                var objThumb = new Thumbnailv2.Thumbnail();
                objThumb.InputImage = mappath;
                objThumb.W = Constant.NewAvatar1Width;
                objThumb.H = Constant.NewAvatar1Height;
                objThumb.CreateThumb();

                if (Constant.NewAvatar2Width > 0 && Constant.NewAvatar2Height > 0)
                {
                    objThumb.W = Constant.NewAvatar2Width;
                    objThumb.H = Constant.NewAvatar2Height;
                    objThumb.CreateThumb();
                }

                if (Constant.NewAvatar3Width > 0 && Constant.NewAvatar3Height > 0)
                {
                    objThumb.W = Constant.NewAvatar3Width;
                    objThumb.H = Constant.NewAvatar3Height;
                    objThumb.CreateThumb();
                }

                objThumb = null;

                response.Success = true;
                response.Message = "Upload thanh cong";
                response.Data = path;
                response.ExtData = path + ".thumb" + Constant.NewAvatar1Width + "x" + Constant.NewAvatar1Height + ".jpg";
            }

            return response;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}